<?php
/*	  Copyright (C) 2011  João Dias de Carvalho Neto

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

	require_once 'MyConfig.php';

	class DBConnection
	{
			
		/***
		 * Get an instance of Mysql Connection 
		 */
		private function getConnection()
		{
			try 
			{
				$ret = mysql_connect(MyConfig::$DB_HOSTNAME,
					MyConfig::$DB_USERNAME,MyConfig::$DB_PASSWORD);
				mysql_selectdb(MyConfig::$DB_NAME,$ret);
				mysql_set_charset(MyConfig::$DB_CHARSET,$ret);
				return $ret;
			}
			catch (Exception $e)
			{
				throw new Exception($e->getMessage(), $e->getCode());
			}
		}
		
		/***
		 * Method to prevent SQL Injections
		 */
		public static function preventSQLInjection($string)
		{
 			 if(get_magic_quotes_gpc())  // prevents duplicate backslashes
  			 {
			    $string = stripslashes($string);
  			 }
  			 if (phpversiolinesn() >= '4.3.0')
  			 {
    			$string = mysql_real_escape_string($string);
  			 }
 			 else
  			 {
			    $string = mysql_escape_string($string);
  			 }
			//If are so dummy and still wants keep root as user in mysql
			//preg_replace should help you in a possible SQL injection attack
  			$badWords =  array("/delete/i", "/update/i","/union/i","/insert/i",
  				"/drop/i","/http/i","/--/i");  				  			
  			
  			return preg_replace($badWords,"", $string);
		}
		
		public function executeQuery($sql)
		{			
			try 
			{
				$ret = mysql_query($sql,$this->getConnection());
				if ($ret==false)
				{
					throw new Exception(mysql_error(), '00');
				}
				$rst = array();
				$i = 0;
			
				while ($row = mysql_fetch_array($ret,MYSQL_BOTH))
				{
					$rst[$i] = $row;
					$i++;
				}
				return $rst;
			}
			catch(Exception $e)
			{
				throw new Exception($e->getMessage(), $e->getCode());
			}			
		}
		
		/***
		 * Method to execute a no read SQL Statement
		 */
		public function executeNonRead($sql)
		{
			try 
			{
				$ret = mysql_query($sql,$this->getConnection());
				if ($ret==false)
				{
					throw new Exception(mysql_error(), '00');
				}
				return $ret;			
			}
			catch(Exception $e)
			{
				throw new Exception($e->getMessage(), $e->getCode());
			}									
		}
		
		/***
		 * Execute a Scalar SQL Statement
		 */
		public function executeScalar($sql)
		{
			try 
			{
				$ret = mysql_query($sql,$this->getConnection());
				if ($ret==false)
				{
					throw new Exception(mysql_error(), '00');
				}
				$array = mysql_fetch_array($ret);
				return $array[0];			
			}
			catch(Exception $e)
			{
				throw new Exception($e->getMessage(), $e->getCode());
			}												
		}
		
		/***
		 * Method to simplify a check SQL Statement
		 */
		public function checkIfExists($field, $table, array $values)
		{
			//Mount the base Query SQL Statement
			$sql = " SELECT $field FROM $table WHERE 1=1 ";
			
			//Search for an array contenting a relation of Field -> Value
			for ($i = 0; i <=count($values)-1;$i++)
			{	$f = DBConnection::preventSQLInjection($values[$i]['field']);
				$v = DBConnection::preventSQLInjection($values[$i]['value']);		
				$sql .= " AND $f=$v ";				
			}
			
			try 
			{
				$ret = mysql_query($sql,$this->getConnection());
				if ($ret==false)
				{
					throw new Exception(mysql_error(), '00');
				}

				return count(mysql_fetch_array($ret)) > 0;
			}
			catch(Exception $e)
			{
				throw new Exception($e->getMessage(), $e->getCode());
			}						
		}
		
	}

?>